<template>
    <panelHead :route="route"/>
    <el-card class="page-container">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="formInline" class="form-search">
            <el-form-item label="用户名搜索">
            <el-input v-model="formInline.user" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item label="权限搜索" >
                <el-select
                    v-model="formInline.permission"
                    placeholder="请选择用户权限"
                    clearable
                >
                    <el-option label="管理员" value="0" />
                    <el-option label="普通用户" value="1" />
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间搜索">
            <el-date-picker
                v-model="formInline.date"
                type="date"
                placeholder="请选择时间"
                clearable
            />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="userList" :icon="Search" >搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 用户列表 -->
        <el-table :data="users" style="width: 100%;" :header-cell-style="{textAlign: 'center'}" :cell-style="{ textAlign: 'center' }" >
            <el-table-column label="用户id" width="90" prop="id"></el-table-column>
            <el-table-column label="用户名" prop="username" width="150"></el-table-column>
            <el-table-column label="用户昵称" prop="nickname" width="100"></el-table-column>
            <el-table-column label="用户权限" width="150">
                <template #default="{ row }">
                    <div>
                        <el-select v-model="row.permission" @change="updateUserPermission(row)">
                            <el-option label="管理员" value="0"></el-option>
                            <el-option label="普通用户" value="1"></el-option>
                        </el-select>
                    </div>
                </template>
            </el-table-column>
            
            <el-table-column label="邮箱" prop="email" width="200"></el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="200"> </el-table-column>
            <el-table-column label="操作" width="250">
                <template #default="{ row }">
                    <!-- <el-button :icon="Edit" circle plain type="primary"></el-button> -->
                    <el-button :icon="Delete" type="danger" @click="deleteUser(row)">删除</el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="paginationData.pageNum" v-model:page-size="paginationData.pageSize" :page-sizes="[5, 8, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />                    
    </el-card>
</template>
<script setup>
import { userListService } from '@/api/user.js'
import { ref, reactive, onMounted } from 'vue';
import dayjs from 'dayjs';
import {  Delete,  Search } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const paginationData = reactive({
    pageNum: 1,
    pageSize: 8
})
const username = ref('')
const permission = ref('')
const createTime = ref(null)  //  添加创建时间搜索变量
const users = ref([])
const total = ref(0)
const formInline = reactive({
    user: '',        // 用户名搜索
    permission: '',      // 用户权限搜索
    date: ''       // 创建时间搜索
})
//const username = localStorage.getItem('min_userName')
const userList = async () => {
    let params = {
        pageNum: paginationData.pageNum,
        pageSize: paginationData.pageSize,
        username: formInline.user || null,
        permission: formInline.permission || null,
        createTime: formInline.date ? formInline.date.toISOString().split('T')[0] : null 
    }
    try {
        let result = await userListService.get(params);
        console.log("result",result);
        if (result.data.code === 0) {
            total.value = result.data.data.total;
            users.value = result.data.data.items.map(user => ({
                ...user,
                //permission: user.permission === '0' ? '管理员' : '普通用户',
                permission: String(user.permission),
                createTime: dayjs(user.createTime).format('YYYY-MM-DD HH:mm:ss')  // 格式化创建时间
            }));
            console.log(users,"users")
        }
        
    } catch (error) {
        console.error('获取用户列表失败', error);
    }
}
onMounted(() => {
    userList();
});
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    paginationData.pageSize = size
    userList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    paginationData.pageNum = num
    userList()
}
const resetSearch = () => {
    username.value = '';
    permission.value = '';
    createTime.value = null;  // 重置创建时间搜索框
    userList();
}
const currentPermission = ref('')
const updateUserPermission = async (user) => {
    //console.log(user.id,"user.id")
    try {
        const requestData = new FormData();
        requestData.append('id', user.id);  
        requestData.append('permission', user.permission);  

        console.log("传递给后端的数据：", requestData.toString());

        const response = await userListService.update(requestData);

        if (response.data.code === 0) {
            ElMessage({
            message: "用户权限修改成功",
            type: 'success',
        })
        }else {
            alert('用户权限修改失败: ' + response.data.message);
        }
    } catch (error) {
        console.error('用户权限修改失败', error);
    }
}

/* const deleteUser = async (userId) => {
    ElMessageBox.confirm(
        '你确认要删除该用户吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    try {
        await userListService.delete({ id: userId });
        ElMessage({
            message: "用户删除成功",
            type: 'success',
        })
        userList();
    } catch (error) {
        
        console.error('删除用户失败', error);
    }
} */
const deleteUser = (userId) => {
    ElMessageBox.confirm(
        '你确认要删除该用户吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(async () => {
            //调用接口
            let result = await userListService.delete(userId.id);
            console.log('界面查看删除用户id',userId.id);
            console.log('result',result);
            if (result.data.code === 0) {  // 确认请求成功
                ElMessage({
                    type: 'success',
                    message: '用户删除成功',
                });
            //刷新列表
            userList();
            }else {
                ElMessage({
                    type: 'error',
                    message: '删除用户失败: ' + result.data.message,
                });
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '用户取消了删除',
            })
        })
}
</script>

<style lang="less" scoped>
	.page-container {
		padding: 2px 10px;
        margin-top: 15px;
		background: #e8edf0;
		border-color: #e8edf0;
		position: relative;

		.header {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .form-search .el-input {
            --el-input-width: 160px;
        }

        .form-search .el-select {
            --el-select-width: 180px;
        }
    
	}
	.editor {
    width: 100%;
    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>